/*
 * @Author: 非幡动 438484791@qq.com
 * @Date: 2024-06-27 09:13:39
 * @LastEditors: 非幡动 438484791@qq.com
 * @LastEditTime: 2024-06-27 16:40:39
 * @FilePath: \dicomReaderReact\src\App.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import './App.css'
import React from 'react';
import * as cornerstone from "cornerstone-core";
import * as cornerstoneMath from "cornerstone-math";
import * as cornerstoneTools from "cornerstone-tools";
import Hammer from "hammerjs";
import * as cornerstoneWebImageLoader from "cornerstone-web-image-loader";
import cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader';
import dicomParser from 'dicom-parser';

cornerstoneTools.external.cornerstone = cornerstone;
cornerstoneTools.external.cornerstoneMath = cornerstoneMath;
cornerstoneWebImageLoader.external.cornerstone = cornerstone;
// cornerstoneWADOImageLoader.external.cornerstone = cornerstone;
cornerstoneWADOImageLoader.external.cornerstone = cornerstone;
cornerstoneWADOImageLoader.external.dicomParser = dicomParser;
cornerstoneWADOImageLoader.configure({
  // 配置加载程序，例如 Web Worker 选项
});

cornerstoneTools.external.Hammer = Hammer;

const divStyle = {
  width: "512px",
  height: "512px",
  position: "relative",
  color: "white"
};

const bottomLeftStyle = {
  bottom: "5px",
  left: "5px",
  position: "absolute",
  color: "white"
};

const bottomRightStyle = {
  bottom: "5px",
  right: "5px",
  position: "absolute",
  color: "white"
};
let imageIds = [];
let viewport = cornerstone.getDefaultViewport(null, undefined)
let loaded = false;
class CornerstoneElement extends React.Component {
  constructor() {
    super();
    // this.state = {
    //   ,
    // };
    this.onImageRendered = this.onImageRendered.bind(this);
    this.onNewImage = this.onNewImage.bind(this);
    this.onWindowResize = this.onWindowResize.bind(this);
  }

  onChangeFile = (event) => {
    const files = event.target.files;
    if (!files) {
      return;
    }
    for (let i = 0; i < files.length; i++){
      imageIds[i] = cornerstoneWADOImageLoader.wadouri.fileManager.add(files[i]);
    }
    console.log(imageIds)
    this.loadAndViewImage(imageIds[0]);
    // loadAndReturnViewImage(imageIds);
  };

  loadAndViewImage = (imageId) => {
    const element = this.element;

    cornerstone.loadImage(imageId).then(function(image) {
        viewport = cornerstone.getDefaultViewportForImage(element, image);
        cornerstone.displayImage(element, image, viewport);
        if(loaded === false) {
          // cornerstoneTools.addTool()
            // cornerstoneTools.mouseInput.enable(element);
            // cornerstoneTools.mouseWheelInput.enable(element);
            // cornerstoneTools.wwwc.activate(element, 1); // ww/wc is the default tool for left mouse button
            // cornerstoneTools.pan.activate(element, 2); // pan is the default tool for middle mouse button
            // cornerstoneTools.zoom.activate(element, 4); // zoom is the default tool for right mouse button
            // cornerstoneTools.zoomWheel.activate(element); // zoom is the default tool for middle mouse wheel

            // cornerstoneTools.imageStats.enable(element);
            loaded = true;
        }

    }, function(err) {
        alert(err);
    });
}

  render() {
    return (
      <div>
        <input type="file" onChange={this.onChangeFile} 
        webkitdirectory="true" multiple />
        <div
          className="viewportElement"
          style={divStyle}
          ref={input => {
            this.element = input;
          }}
        >
          <canvas className="cornerstone-canvas" />
          <div style={bottomLeftStyle}>Zoom: {viewport.scale}</div>
          <div style={bottomRightStyle}>
            WW/WC: {viewport.voi.windowWidth} /{" "}
            {viewport.voi.windowCenter}
          </div>
        </div>
      </div>
    );
  }

  onWindowResize() {
    console.log("onWindowResize");
    cornerstone.resize(this.element);
  }

  onImageRendered() {
    const viewport = cornerstone.getViewport(this.element);
    console.log(viewport);

    this.setState({
      viewport
    });

    console.log(this.state.viewport);
  }

  onNewImage() {
    const enabledElement = cornerstone.getEnabledElement(this.element);

    // this.setState({
    //   imageId: enabledElement.image.imageId
    // });
  }

  async componentDidMount() {
    const element = this.element;

    // Enable the DOM Element for use with Cornerstone
    cornerstone.enable(element);

    // Load the first image in the stack
    await imageIds[0] 
    cornerstone.loadImage(imageIds[0]).then(image => {
      // Display the first image
      cornerstone.displayImage(element, image);

      // Add the stack tool state to the enabled element
      const stack = imageIds[0];
      cornerstoneTools.addStackStateManager(element, ["stack"]);
      cornerstoneTools.addToolState(element, "stack", stack);

      // cornerstoneTools.mouseInput.enable(element);
      // cornerstoneTools.mouseWheelInput.enable(element);
      // cornerstoneTools.wwwc.activate(element, 1); // ww/wc is the default tool for left mouse button
      // cornerstoneTools.pan.activate(element, 2); // pan is the default tool for middle mouse button
      // cornerstoneTools.zoom.activate(element, 4); // zoom is the default tool for right mouse button
      // cornerstoneTools.zoomWheel.activate(element); // zoom is the default tool for middle mouse wheel

      // cornerstoneTools.touchInput.enable(element);
      // cornerstoneTools.panTouchDrag.activate(element);
      // cornerstoneTools.zoomTouchPinch.activate(element);

      // element.addEventListener(
      //   "cornerstoneimagerendered",
      //   this.onImageRendered
      // );
      // element.addEventListener("cornerstonenewimage", this.onNewImage);
      // window.addEventListener("resize", this.onWindowResize);
    });
  }

  componentWillUnmount() {
    const element = this.element;
    element.removeEventListener(
      "cornerstoneimagerendered",
      this.onImageRendered
    );

    element.removeEventListener("cornerstonenewimage", this.onNewImage);

    window.removeEventListener("resize", this.onWindowResize);

    cornerstone.disable(element);
  }

  componentDidUpdate(prevProps, prevState) {
    const stackData = cornerstoneTools.getToolState(this.element, "stack");
    const stack = stackData.data[0];
    stack.currentImageIdIndex = this.state.stack.currentImageIdIndex;
    stack.imageIds = this.state.stack.imageIds;
    cornerstoneTools.addToolState(this.element, "stack", stack);

    const imageId = stack.imageIds[stack.currentImageIdIndex];
    cornerstoneTools.scrollToIndex(this.element, stack.currentImageIdIndex);
  }
}


// const stack = {
//   imageIds: [imageId],
//   currentImageIdIndex: 0
// };


function App() {

  return (
    <>
      <div>
        <h2>Cornerstone React Component Example</h2>
        <CornerstoneElement />
      </div>
    </>
  )
}

export default App
